package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.user.dto.LoginDto;
import com.heima.user.entity.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断是否缺少参数
        if((StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword()))){

            //根据电话号码查询用户
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone,dto.getPhone());
            ApUser one = this.getOne(queryWrapper);
            if(one==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }

            //再比较密码
            String password_mi = DigestUtils.md5Hex(dto.getPassword() + one.getSalt());
            if (!StringUtils.equals(one.getPassword(),password_mi)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            Map resultMap = new HashMap();
            //去除one对象中的敏感数据
            one.setPassword("");
            one.setPhone("");
            one.setSalt("");
            resultMap.put("user",one);

            Map<String, Object> claimMaps = new HashMap<>();
            claimMaps.put("userId",one.getId());
            claimMaps.put("name",one.getName());
            String token = AppJwtUtil.getToken(claimMaps);

            resultMap.put("token",token);
            return ResponseResult.okResult(resultMap);

        }else{
            //不登录先看看
            Map resultMap = new HashMap();
            ApUser one = new ApUser();
            //去除one对象中的敏感数据
            one.setId(0);
            resultMap.put("user",one);

            Map<String, Object> claimMaps = new HashMap<>();
            claimMaps.put("userId",1);
            claimMaps.put("name","");
            String token = AppJwtUtil.getToken(claimMaps);
            resultMap.put("token",token);
            return ResponseResult.okResult(resultMap);
        }
    }
}
